# @time     :2022/2/19
# @Author   :Simple
# @FileName :device
"""
测试前准备：
    自动获取连接的设备信息
"""
import os
import re

from util.logger import log as logger


def read_android_info():
    """
    获取安卓设备信息，然后组合成对应的desired_caps
    """
    cmd_adb = "adb kill-server && adb server && adb devices"
    android_devices = os.popen(cmd_adb).readlines()
    android_device_list = []
    if len(android_devices) > 1:
        for device in android_devices[1:-1]:
            try:
                device_id = device.split("\t")[0]
                # 读取设备系统版本号
                android_version = os.popen(f"adb -s {device_id} shell getprop ro.build.version.release").read()\
                    .replace("\n", "")
                # 读取设备型号
                android_model = os.popen(f"adb -s {device_id} shell getprop ro.product.model").\
                    read().replace(" ", "").replace("\n", "")
                android_device_list.append({
                    "device_name": android_model,
                    "platform_version": android_version,
                    "udid": device_id,
                })
            except Exception as e:
                logger.info(e)
                continue
        logger.info(f"read Android device {android_device_list}")
    else:
        logger.warning(f"read Android device is none")

    return android_device_list


def read_ios_info():
    """
    获取ios设备信息，然后组合成对应的desired_caps
    """
    # xcode13.0已经弃用instruments，使用xctrace代替
    # cmd_instruments = "instruments -s devices | grep -v Simulator | grep -v MacBook | grep -v null | awk 'NR>1{print}'"
    cmd_xctrace = "xcrun xctrace list devices | sed '/Simulators/,$d' | grep -v Devices | grep -v MacBook | sed '/^$/d'"
    ios_devices = os.popen(cmd_xctrace).read()
    info = re.findall(r"(.+) \((.+)\) \((.+)\)", ios_devices)
    ios_device_list = []
    if len(info) > 0:
        for device in info:
            device_name = device[0]
            device_version = device[1]
            udid = device[2]
            ios_device_list.append({
                "device_name": device_name,
                "platform_version": device_version,
                "udid": udid,
            })
        logger.info(f"read ios device:{ios_device_list}")
    else:
        logger.warning(f"read ios device is none")
    return ios_device_list


def get_devices():
    """
    自动识别连接的手机设备
    实现即插即用
    """
    android = read_android_info()
    ios = read_ios_info()
    devices_list = android + ios
    if len(devices_list) > 0:
        logger.info(f"devices_list {devices_list}")
        return devices_list
    else:
        logger.error("没有找到连接的设备!!!")
        raise Exception("没有找到连接的设备!!!")


def init_device_info():
    logger.info('初始化设备信息>>>')
    device_infos = get_devices()
    for i in range(0, len(device_infos)):
        server_port = 4723 + 2 * i
        system_port = 8200 + i
        device_infos[i]["server_port"] = server_port
        device_infos[i]["system_port"] = system_port
    # logger.info(f"将设备信息写入文件 {DEVICE_CAPS}")
    # write_yaml(DEVICE_CAPS, device_infos)
    return device_infos


def check_device(device):
    """
    检查设备 ios or Android
    """
    if device is None or device == '':
        raise Exception('device name Cannot be empty!!!')
    if not isinstance(device, str):
        device = str(device)
    if "iphone" in device.lower() or 'ipad' in device.lower():
        return "ios"
    else:
        return "Android"

